package com.qys.livesMall.system.source.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.cache.RedisCache;
import com.qys.livesMall.cache.utils.CacheUtil;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MD5Util;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.framework.view.QysPage;
import com.qys.livesMall.system.constants.Constants;
import com.qys.livesMall.system.source.domain.dto.dict.AddDict;
import com.qys.livesMall.system.source.domain.dto.dict.AddDictInfo;
import com.qys.livesMall.system.source.domain.dto.dict.DictDataSearch;
import com.qys.livesMall.system.source.domain.dto.dict.EditDict;
import com.qys.livesMall.system.source.domain.entity.SysDictData;
import com.qys.livesMall.system.source.domain.vo.dict.DictDateVO;
import com.qys.livesMall.system.source.domain.vo.dict.DictVO;
import com.qys.livesMall.system.source.mapper.SysDictDataMapper;
import com.qys.livesMall.system.source.service.ISysDictDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author wanglei
 */
@Service
public class SysDictDataServiceImpl implements ISysDictDataService {
    @Autowired
    private SysDictDataMapper dictDataMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 根据条件分页查询字典数据
     *
     * @param search 字典数据信息
     * @return 字典数据集合信息
     */
    @Override
    public QysPage<DictVO> selectDictDataList(DictDataSearch search) {
        Page<SysDictData> sPage = dictDataMapper.selectDictDataList(new Page<>(search.getPageNum(), search.getPageSize()), search);
        return QysPage.to(sPage, DictVO.class);
    }

    /**
     * 根据字典类型和字典键值查询字典数据信息
     *
     * @param dictType  字典类型
     * @param dictValue 字典键值
     * @return 字典标签
     */
    @Override
    public String selectDictLabel(String dictType, String dictValue) {
        return dictDataMapper.selectDictLabel(dictType, dictValue);
    }

    /**
     * 根据字典数据ID查询信息
     *
     * @param dictCode 字典数据ID
     * @return 字典数据
     */
    @Override
    public R<DictDateVO> selectDictDataById(Long dictCode) {
        SysDictData dictData= dictDataMapper.selectDictDataById(dictCode);
        if (dictData==null){
            return R.fail("未发现字典");
        }
        LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDictValue,dictData.getDictValue());
        queryWrapper.eq(SysDictData::getDictType,dictData.getDictType());
        List<SysDictData> list=dictDataMapper.selectList(queryWrapper);
        DictDateVO vo=new DictDateVO();
        BeanUtils.copyProperties(dictData,vo);
        List<AddDictInfo> addDictInfos=new ArrayList<>();
        for (SysDictData sysDictData:list){
            AddDictInfo addDictInfo=new AddDictInfo();
            BeanUtils.copyProperties(sysDictData,addDictInfo);
            addDictInfos.add(addDictInfo);
        }
        vo.setAddDictInfos(addDictInfos);
        return R.ok(vo);
    }

    /**
     * 批量删除字典数据信息
     *
     * @param dictCodes 需要删除的字典数据ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDictDataByIds(Long[] dictCodes) {
        for (Long dictCode : dictCodes) {
            SysDictData dictData= dictDataMapper.selectDictDataById(dictCode);
            if (dictData!=null){
                LambdaQueryWrapper<SysDictData> queryWrapper=new LambdaQueryWrapper<>();
                queryWrapper.eq(SysDictData::getDictValue,dictData.getDictValue());
                queryWrapper.eq(SysDictData::getDictType,dictData.getDictType());
                List<SysDictData> list=dictDataMapper.selectList(queryWrapper);
                List<Long> ids=list.stream().map(SysDictData::getDictCode).toList();
                dictDataMapper.deleteDictDataByIds(ids.toArray(Long[]::new));
                getDictTypeKey(dictData.getDictType());
            }
        }
    }

    public void getDictTypeKey(String dictType){
        List<SysDictData> dictData = dictDataMapper.selectDictDataByType("national_language_code","zh_CN");
        if (CollectionUtils.isNotEmpty(dictData)){
            for (SysDictData data:dictData){
                String key = CacheUtil.getKey(Constants.SysRedisKeyPrefix.DICT, data.getDictValue()+":"+dictType);
                redisCache.deleteObject(key);
            }
        }
    }

    /**
     * 新增保存字典数据信息
     *
     * @param addDict 字典数据信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R insertDictData(AddDict addDict) {
        for (AddDictInfo addDictInfo:addDict.getAddDictInfos()){
            SysDictData dictData=new SysDictData();
            BeanUtils.copyProperties(addDictInfo,dictData);
            BeanUtils.copyProperties(addDict,dictData);
            dictDataMapper.insert(dictData);
        }
        getDictTypeKey(addDict.getDictType());
        return R.ok();
    }

    /**
     * 新增保存字典数据信息
     *
     * @param addDict 字典数据信息
     * @return 结果
     */
    public R insertDictDataAutoKey(AddDict addDict) {
        boolean isExist=true;
        String key=null;
        while (isExist){
            //生成key
            key= MD5Util.randomString(5);
            isExist=isExist(addDict.getDictType(),key);
        }
        SysDictData dictData=new SysDictData();
        BeanUtils.copyProperties(addDict,dictData);
        dictData.setDictValue(key);
        int row = dictDataMapper.insertDictData(dictData);
        if (row > 0) {
            getDictTypeKey(dictData.getDictType());
        }
        return R.ok();
    }

    /**
     * 修改保存字典数据信息
     *
     * @param data 字典数据信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateDictData(EditDict data) {
        for (AddDictInfo addDictInfo:data.getAddDictInfos()){
            if (null == addDictInfo.getDictCode()){
                SysDictData dictData=new SysDictData();
                BeanUtils.copyProperties(data,dictData);
                BeanUtils.copyProperties(addDictInfo,dictData);
                dictData.setDictValue(data.getDictValue());
                dictDataMapper.insert(dictData);
            }else {
                SysDictData dictData=dictDataMapper.selectDictDataById(addDictInfo.getDictCode());
                if (dictData==null){
                    return R.fail("未发现字典");
                }
                BeanUtils.copyProperties(data,dictData);
                BeanUtils.copyProperties(addDictInfo,dictData);
                dictData.setDictValue(data.getDictValue());
                dictDataMapper.updateDictData(dictData);
            }

        }
        getDictTypeKey(data.getDictType());
        return R.ok();
    }

    public boolean isExist(String type, String key) {
        SysDictData dataInfo=dictDataMapper.getDataInfo(type,key);
        if (dataInfo==null){
            return false;
        }
        return true;
    }
}
